import requests
import json
import execjs
import base64
import AntiCAP
import ddddocr
session = requests.session()
# 假设demo2.js已经在当前目录中，并包含rsa_enc函数
with open("demo2.js", "r", encoding="utf-8") as f:
    js_code = f.read()
js_com = execjs.compile(js_code)
# 代理设置
proxies = {
    "http": "http://127.0.0.1:7890",
    "https": "http://127.0.0.1:7890",
}


def gen_code():
    # 加密参数
    par = {
        "key": "query"
    }
    params = js_com.call("rsa_enc", par)
    print("params==>", params)

    # 设置请求头
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,ar;q=0.7",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/json;charset=UTF-8",
        "Origin": "https://www.ynjzjgcx.com",
        "Pragma": "no-cache",
        "Referer": "https://www.ynjzjgcx.com/dataPub/enterprise",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0",
        "appId": "84ded2cd478642b2",
        "isToken": "false",
        "sec-ch-ua": "\"Not;A=Brand\";v=\"99\", \"Microsoft Edge\";v=\"139\", \"Chromium\";v=\"139\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\""
    }

    # 请求URL
    url = "https://www.ynjzjgcx.com/prod-api/mohurd-pub/vcode/genVcode"

    # 请求数据
    data = {
        "params": params
    }

    # 发送请求
    data = json.dumps(data, separators=(',', ':'))
    response = session.post(url, headers=headers, data=data, proxies=proxies)
    json_data = response.json()
    # print("原始响应:", json_data)

    # 解析数据
    if json_data['code'] == 200:
        # 解析内层的JSON字符串
        inner_data = json.loads(json_data['data'])

        # 提取数据
        slide_id = inner_data['slideId']
        small_image_b64 = inner_data['smallImage']
        big_image_b64 = inner_data['bigImage']

        print("滑块ID:", slide_id)
        print("小图(滑块)长度:", len(small_image_b64))
        print("大图(背景)长度:", len(big_image_b64))

        # 解码Base64并保存图片
        small_image_bytes = base64.b64decode(small_image_b64)
        big_image_bytes = base64.b64decode(big_image_b64)

        # 保存图片到文件
        with open("smallImage.png", "wb") as f:
            f.write(small_image_bytes)
        print("滑块图片已保存为 smallImage.png")

        with open("bigImage.png", "wb") as f:
            f.write(big_image_bytes)
        print("背景图片已保存为 bigImage.png")

        # 返回解析后的数据结构
        parsed_result = {
            "slideId": slide_id,
            "smallImageLength": len(small_image_b64),
            "bigImageLength": len(big_image_b64)
        }
        print("解析结果:", parsed_result['slideId'])
        return parsed_result['slideId']
    else:
        print("请求失败:", json_data['msg'] if 'msg' in json_data else "未知错误")


def page(slideId: str, dist: int):
    parr = {
        "pageNum": 1,
        "pageSize": 10,
        "certificateType": "",
        "name": "",
        "slideId": slideId,
        "key": "query",
        "width": dist
    }
    params = js_com.call("rsa_enc", parr)
    print("params==>", params)
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,ar;q=0.7",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/json;charset=UTF-8",
        "Origin": "https://www.ynjzjgcx.com",
        "Pragma": "no-cache",
        "Referer": "https://www.ynjzjgcx.com/dataPub/enterprise",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0",
        "appId": "84ded2cd478642b2",
        "isToken": "false",
        "sec-ch-ua": "\"Not;A=Brand\";v=\"99\", \"Microsoft Edge\";v=\"139\", \"Chromium\";v=\"139\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\""
    }
    url = "https://www.ynjzjgcx.com/prod-api/mohurd-pub/dataServ/findBaseEntDpPage"
    data = {
        "params": params
    }
    data = json.dumps(data, separators=(',', ':'))
    response = session.post(url, headers=headers, data=data, proxies=proxies)
    print(response.status_code)
    print(response.text)
# example.py
def calculate_slide_distance():
    # example.py

    import base64
    import AntiCAP

    # 读取滑块图片（小块）
    with open("smallImage.png", "rb") as f:
        target_base64 = base64.b64encode(f.read()).decode('utf-8')

    # 读取背景图片（带缺口的大图）
    with open("bigImage.png", "rb") as f:
        background_base64 = base64.b64encode(f.read()).decode('utf-8')

    Atc = AntiCAP.Handler(show_banner=True)

    result = Atc.Slider_Match(target_base64=target_base64,
                              background_base64=background_base64
                              )

    print(result)
if __name__ == '__main__':
    # slideId=gen_code()
    # dist=int(input("请输入距离："))
    # page(slideId,dist)
    res=calculate_slide_distance()
